#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstdlib>

// 将mutex包装成一个类，对其初始化、销毁、加锁、解锁都有类成员函数完成
class Mutex
{
public:
    Mutex(pthread_mutex_t *pmutex) : _pmutex(pmutex)
    {
        int ret = pthread_mutex_init(_pmutex, nullptr);
        if (ret != 0)
            exit(1);
    }

    void lock()
    {
        int ret = pthread_mutex_lock(_pmutex);
        if (ret != 0)
            exit(2);
    }

    void unlock()
    {
        int ret = pthread_mutex_unlock(_pmutex);
        if (ret != 0)
            exit(3);
    }

    pthread_mutex_t *getmutex()
    {
        return _pmutex;
    }

    ~Mutex()
    {
        int ret = pthread_mutex_destroy(_pmutex);
        if (ret != 0)
            exit(4);
    }

private:
    pthread_mutex_t *_pmutex;
};

class lockGuard
{
public:
    lockGuard(Mutex *mutex) : _mutex(mutex)
    {
        _mutex->lock();
    }

    ~lockGuard()
    {
        _mutex->unlock();
        usleep(1000);
    }

private:
    Mutex *_mutex;
};